import React, { useRef, useState } from 'react';
import { Button, message, Form, Input, Radio, Spin, TreeSelect, Row, Col, InputNumber } from 'antd';
import { DrawerForm } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PlusOutlined, FormOutlined } from '@ant-design/icons';
import { add, edit, update, getPidList } from '@/services/admin/auth/rule/api';
interface PorpsType {
  onConfirm: () => void;
  id?: number;
  pid?: number;
  disabled?: boolean;
}
const FormIndex: React.FC<PorpsType> = (porps) => {
  const restFormRef = useRef<ProFormInstance>();
  const [loading, setLoading] = useState(porps.id ? false : true);
  const [pidList, setPidList] = useState<any>([]);
  const [pidListLoading, setPidListLoading] = useState<boolean>(false);

  const formData: API.AdminRuleForm = {
    id: null,
    path: '',
    url: '',
    redirect: '',
    icon: '',
    name: '',
    type: 1,
    status: 1,
    auth_open: 1,
    level: 1,
    affix: 0,
    pid: 0,
    sort: 1,
  };
  return (
    <DrawerForm<API.AdminRuleForm>
      layout="horizontal"
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 20 }}
      formRef={restFormRef}
      initialValues={formData}
      title={porps.id ? '编辑' : '添加'}
      autoFocusFirstInput
      isKeyPressSubmit
      trigger={
        porps.id ? (
          <Button type="primary" disabled={porps.disabled ? true : false} size="small">
            <FormOutlined />
            编辑
          </Button>
        ) : porps.pid ? (
          <Button type="primary" size="small">
            <PlusOutlined />
            添加子菜单
          </Button>
        ) : (
          <Button type="primary">
            <PlusOutlined />
            添加
          </Button>
        )
      }
      drawerProps={{
        forceRender: true,
        destroyOnClose: true,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              loading={loading ? false : true}
              key="extra-reset"
              onClick={async () => {
                const id = props.form?.getFieldValue('id');
                if (id) {
                  await setLoading(false);
                  const res = await edit(id);
                  if (res.status === 20000) {
                    restFormRef.current?.setFieldsValue(res.data);
                    await setLoading(true);
                  }
                } else {
                  props.reset();
                }
              }}
            >
              重置
            </Button>,
          ];
        },
      }}
      onFinish={async (values: any) => {
        let res: any = {};
        if (porps.id) {
          res = await update(porps.id, values);
        } else {
          res = await add(values);
        }
        if (res.status === 20000) {
          message.success(res.message);
          porps.onConfirm();
          return true;
        }
        return false;
      }}
      onVisibleChange={async (visible) => {
        if (visible) {
          if (porps.pid) {
            await restFormRef.current?.setFieldsValue({ pid: porps.pid });
          }
          if (porps.id) {
            await setLoading(false);
            const res = await edit(porps.id);
            if (res.status === 20000) {
              await restFormRef.current?.setFieldsValue(res.data);
              await setLoading(true);
            }
          }
          const data: { id?: number } = {};
          if (porps.id) {
            data.id = porps.id;
          }
          await setPidListLoading(true);
          const pidRes = await getPidList(data);
          if (pidRes.status == 20000) {
            await setPidListLoading(false);
            await setPidList(pidRes.data);
          }
        }
      }}
    >
      <Spin spinning={loading ? false : true}>
        {loading && (
          <>
            <Form.Item
              label="父级菜单"
              name="pid"
              rules={[{ required: true, message: '请选择父级菜单' }]}
            >
              <TreeSelect
                treeData={pidList}
                allowClear
                placeholder="请选择父级菜单"
                loading={pidListLoading}
              />
            </Form.Item>
            <Form.Item
              label="菜单名称"
              name="name"
              rules={[{ required: true, message: '请输入菜单名称' }]}
            >
              <Input maxLength={100} allowClear placeholder="请输入菜单名称" />
            </Form.Item>

            <Form.Item label="标识" name="path">
              <Input maxLength={100} allowClear placeholder="请输入标识" />
            </Form.Item>
            <Form.Item label="路由文件" name="url">
              <Input maxLength={100} allowClear placeholder="请输入路由文件" />
            </Form.Item>
            <Form.Item label="重定向路径" name="redirect">
              <Input maxLength={100} allowClear placeholder="请输入重定向路径" />
            </Form.Item>
            <Row>
              <Col span={18}>
                <Form.Item
                  labelCol={{ span: 4 }}
                  wrapperCol={{ span: 20 }}
                  label="图标"
                  name="icon"
                >
                  <Input maxLength={100} allowClear placeholder="请输入图标" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <a
                  href="https://ant.design/components/icon-cn/"
                  target="_blank"
                  style={{ paddingLeft: '10px', lineHeight: '32px' }}
                >
                  去选择图标
                </a>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  name="status"
                  label="状态"
                  rules={[{ required: true, message: '请选择状态' }]}
                >
                  <Radio.Group name="status">
                    <Radio value={0}>隐藏</Radio>
                    <Radio value={1}>显示</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  name="auth_open"
                  label="验证权限"
                  rules={[{ required: true, message: '请选择验证权限' }]}
                >
                  <Radio.Group name="auth_open">
                    <Radio value={0}>否</Radio>
                    <Radio value={1}>是</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  name="affix"
                  label="固定面板"
                  rules={[{ required: true, message: '请选择固定面板' }]}
                >
                  <Radio.Group name="affix">
                    <Radio value={0}>否</Radio>
                    <Radio value={1}>是</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  name="type"
                  label="菜单类型"
                  rules={[{ required: true, message: '请选择菜单类型' }]}
                >
                  <Radio.Group name="type">
                    <Radio value={1}>模块</Radio>
                    <Radio value={2}>目录</Radio>
                    <Radio value={3}>菜单</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item label="排序" name="sort" rules={[{ required: true, message: '请输入排序' }]}>
              <InputNumber
                maxLength={11}
                placeholder="请输入排序"
                min={0}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};
export default FormIndex;
